/**
 * 
 */
package name.gillier.jminify;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import name.gillier.jminify.models.Lien;

import org.apache.commons.validator.UrlValidator;

/**
 * @author Pierre-Yves
 *
 */
public class Shortener {
	
	/**
	 * Logger definition.
	 */
	private static final Logger log = Logger.getLogger(Shortener.class.getName());

	public static String shorten(String url) throws Exception
	{
		log.fine("Calling shortening method with default title");
		return Shortener.shorten(url,"Titre");
	}
	public static String shorten(String url, String titre) throws Exception
	{
		UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES);
		
		if(validator.isValid(url))
		{
			Lien link = new Lien(url, titre);
			
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try
			{
				pm.makePersistent(link);
			}
			catch(Exception e)
			{
				log.severe("Error occured during DB insert for URL <"+url+"> | Message: "+e.getLocalizedMessage());
				throw new IOException("Error during DB insert");
			}
			finally 
			{
				pm.close();
			}
			// Conversion en hexa pour le renvoi de l'URL.
			String hexValue = Integer.toHexString(link.getId().intValue());
			return(hexValue);
		}
		else
		{
			// URI not valid...
			log.warning("Misbuild URL submitted: <"+url+">");
			throw new Exception("Invalid URL provided");
		} 
	}
	
	@SuppressWarnings("unchecked")
	public static Lien expand(String id) throws IOException
	{
		Long intValue = Integer.decode("0x"+id.replace("/", "")).longValue();
		Query query = PMF.get().getPersistenceManager().newQuery(Lien.class);
		query.setFilter(" id == selectedId");
		query.declareParameters("int selectedId");
		
		try 
		{
			List<Lien> liste = (List<Lien>) query.execute(intValue);
			
			if (liste.iterator().hasNext()) {
				// On ne renvoie qu'un seul lien.
				Lien e = liste.iterator().next();
				return(e);
			}
			else
			{
				log.warning("Unknown ID asked: "+id.replace("/", ""));
				throw new IOException("Id not found in database");
			}
		}
		catch(Exception e)
		{
			log.severe("Error occured during DB lookup for ID #"+intValue+" | Message: "+e.getLocalizedMessage());
			throw new IOException("An error occured during lookup.");
		}
		finally
		{
			query.closeAll();
		}
	}
}

